<template>
  <div class="work">
    <div class="work-table">
      <el-form
        :model="searchForm"
        class="search-form"
        inline
        style="margin-bottom: 12px"
      >
        <el-form-item label="报告名称">
          <el-input
            v-model="searchForm.reportName"
            placeholder="请输入报告名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="报告类型">
          <el-select
            v-model="searchForm.reportType"
            placeholder="请选择报告类型"
            clearable
          >
            <el-option label="周报" value="周报" />
            <el-option label="月报" value="月报" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.reportStatus"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="报告生成中" value="报告生成中" />
            <el-option label="报告生成成功" value="报告生成成功" />
            <el-option label="报告生成失败" value="报告生成失败" />
            <el-option label="数据导入失败" value="数据导入失败" />
            <el-option label="报告未生成" value="报告未生成" />
          </el-select>
        </el-form-item>
        <el-form-item class="search-btn-group" style="margin-right: 0">
          <div class="btn-group">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button type="primary" @click="handleIn">新增</el-button>
          </div>
        </el-form-item>
      </el-form>

      <div v-loading="tableLoading">
        <el-table :data="tableData" stripe style="min-height: 300px">
          <!-- 序号 -->
          <el-table-column
            label="序号"
            type="index"
            width="60"
            :index="indexMethod"
          />
          <!-- 报告名称 -->
          <el-table-column
            prop="reportName"
            label="报告名称"
            show-overflow-tooltip
          />
          <!-- 报告类型 -->
          <el-table-column
            prop="reportType"
            label="报告类型"
            show-overflow-tooltip
          />
          <!-- 状态 -->
          <el-table-column
            prop="reportStatus"
            label="状态"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <span
                class="status-dot"
                :class="statusMap[row.reportStatus]?.class"
                :style="{ background: statusMap[row.reportStatus]?.color }"
              ></span>
              <span>{{
                statusMap[row.reportStatus]?.text || row.reportStatus
              }}</span>
            </template>
          </el-table-column>

          <!-- 数据导入时间 -->
          <el-table-column
            prop="createTime"
            label="数据导入时间"
            show-overflow-tooltip
          />
          <!-- 生成时间 -->
          <el-table-column
            prop="updateTime"
            label="生成时间"
            show-overflow-tooltip
          />
          <!-- 操作 -->
          <el-table-column label="操作" width="222">
            <template #default="{ row }">
              <el-button
                type="primary"
                link
                @click="handleGenerateReport(row)"
                :disabled="row.reportStatus !== '报告未生成'"
                :loading="generateLoading[row.id]"
                >报告生成</el-button
              >
              <el-button
                type="primary"
                link
                @click="handleGenerate(row)"
                :disabled="row.reportStatus !== '报告生成成功'"
                >下载</el-button
              >
              <el-button type="primary" link @click="handleDelete(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="pagination-container">
        <span class="total-count">总共 {{ total }} 个项目</span>
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="prev, pager, next, jumper, sizes"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <ReportModal
      v-model="generateDialogVisible"
      :uploadFileUrl="uploadFileUrl"
      :headers="headers"
      @save="handleModalSave"
      @submit="handleModalSubmit"
      @cancel="handleModalCancel"
    />
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getToken } from "@/utils/auth";
import { getList, deleteReport, generateReport } from "./services";
import dayjs from "dayjs";
import ReportModal from "./components/modal.vue";

// 表格数据
const tableData = ref([]);
const total = ref(0);
const tableLoading = ref(false);
// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref(baseUrl + "/nsk/workOrders/importData"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const { proxy } = getCurrentInstance();

const searchForm = reactive({
  workOrderNumber: "", // 工单编号
  source: "", // 工单来源
  createTimeRange: [], // 导入日期区间
  departmentName: "", // 分配科室
  replyContent: "", // 回复建议
});

const statusMap = {
  数据导入失败: { text: "数据导入失败", color: "#bfbfbf", class: "dot-gray" },
  报告未生成: { text: "报告未生成", color: "#409eff", class: "dot-blue" },
  报告生成成功: { text: "报告生成成功", color: "#13ce66", class: "dot-green" },
  报告生成失败: { text: "报告生成失败", color: "#ff4d4f", class: "dot-red" },
  报告生成中: { text: "报告生成中", color: "#13ce66", class: "dot-green" },
};

const indexMethod = (index) =>
  (currentPage.value - 1) * pageSize.value + index + 1;

// 获取表格数据
const fetchTableData = async () => {
  tableLoading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
    };
    if (params.createTimeRange && params.createTimeRange.length === 2) {
      params.params = {
        beginTime: dayjs(params.createTimeRange[0]).format(
          "YYYY-MM-DD 00:00:00"
        ),
        endTime: dayjs(params.createTimeRange[1]).format("YYYY-MM-DD 23:59:59"),
      };
      delete params.createTimeRange;
    }
    const res = await getList(params);
    tableData.value = res.rows || [];
    total.value = res.total || 0;
  } catch (e) {
    // 可选：ElMessage.error('获取数据失败')
  } finally {
    tableLoading.value = false;
  }
};

const handleSearch = () => {
  currentPage.value = 1;
  fetchTableData();
};

const generateDialogVisible = ref(false);
const generateRow = ref(null);
const generateLoading = ref({});

function handleGenerate(row) {
  // 只允许"报告生成成功"状态下载
  if (row.reportStatus !== "已完成" && row.reportStatus !== "报告生成成功") {
    ElMessage.warning("当前状态不可下载，请等待报告生成成功后再下载");
    return;
  }
  if (!row.reportUrl) {
    ElMessage.warning("无可下载的报告");
    return;
  }
  proxy.$download.oss(row.reportUrl);
}

const handleIn = () => {
  generateRow.value = null;
  generateDialogVisible.value = true;
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchTableData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchTableData();
};

const handleModalSave = (data) => {
  // TODO: 暂存逻辑，可用 data 和 generateRow.value
  generateDialogVisible.value = false;
};

const handleModalSubmit = () => {
  fetchTableData(); // 生成报告成功后自动刷新列表
  generateDialogVisible.value = false;
};

const handleModalCancel = () => {
  generateDialogVisible.value = false;
};

const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该报告吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await deleteReport(row.id);
        if (res.code === 200) {
          ElMessage.success("删除成功");
          fetchTableData();
        } else {
          ElMessage.error(res.msg || "删除失败");
        }
      } catch (error) {
        ElMessage.error(error.message || "删除失败");
      }
    })
    .catch(() => {});
};

const handleGenerateReport = (row) => {
  const id = row.id;
  generateLoading.value[id] = true;
  const data = {
    id: row.id,
    reportType: row.reportType,
    reportName: row.reportName,
  };
  generateReport(data)
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success("报告生成成功");
        fetchTableData();
      } else {
        ElMessage.error(res.msg || "报告生成失败");
      }
    })
    .finally(() => {
      generateLoading.value[id] = false;
    });
};

onMounted(() => {
  fetchTableData();
});
</script>

<style lang="scss" scoped>
@import "./index.scss";
.search-form {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  gap: 16px;
}
.search-form .el-form-item {
  margin-bottom: 0;
}
.btn-group {
  display: flex;
  gap: 12px;
}
.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 4px;
  vertical-align: middle;
}
.dot-gray {
  background: #bfbfbf;
}
.dot-blue {
  background: #409eff;
}
.dot-green {
  background: #13ce66;
}
.dot-red {
  background: #ff4d4f;
}
.generate-form {
  .type-row .el-form-item__content {
    align-items: center;
  }
  .upload-row .el-form-item__content {
    flex-direction: column;
    align-items: flex-start;
  }
  .name-row .el-form-item__content {
    align-items: center;
    position: relative;
  }
}
.custom-upload {
  width: 420px;
  height: 180px;
  border: 2px dashed #409eff;
  border-radius: 8px;
  background: #fafcff;
  margin-bottom: 8px;
  .upload-inner {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .upload-icon {
      font-size: 56px;
      color: #409eff;
      margin-bottom: 8px;
    }
    .upload-text {
      color: #606266;
      font-size: 15px;
    }
  }
}
.file-info-bar {
  display: flex;
  align-items: center;
  margin-top: 6px;
  .file-clip {
    color: #bfbfbf;
    font-size: 16px;
  }
  .file-name {
    margin-left: 4px;
    font-size: 14px;
    color: #606266;
  }
  .file-close {
    color: #bfbfbf;
    font-size: 16px;
    margin-left: 4px;
  }
}
.generate-tip {
  color: #faad14;
  background: #fffbe6;
  padding: 2px 10px;
  border-radius: 4px;
  font-size: 13px;
  margin-left: 12px;
  display: inline-block;
  position: absolute;
  right: -210px;
  top: 0;
  white-space: nowrap;
}
.tip-float {
  position: absolute;
  right: 32px;
  top: 340px;
  color: #faad14;
  background: #fffbe6;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 13px;
  z-index: 10;
  box-shadow: 0 2px 8px #eee;
  white-space: nowrap;
}
.footer-btns {
  display: flex;
  justify-content: center;
  gap: 32px;
}
</style>
